﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Devices.Sensors;
using Microsoft.Xna.Framework;

namespace HTML5Application.Extensions
{
    /// <summary>
    /// implementing http://www.w3.org/TR/orientation-event/
    /// </summary>
    public class Html5Bridge : IDisposable
    {
        Accelerometer _accelerometer;
        WebBrowser _browser;
        public Html5Bridge(WebBrowser browser, bool enableAccelerometer)
        {
            _browser = browser;
            browser.ScriptNotify += browser_ScriptNotify;
            if (enableAccelerometer)
            {
                _accelerometer = new Accelerometer();
                _accelerometer.CurrentValueChanged += _accelerometer_CurrentValueChanged;
                _accelerometer.Start();
            }
        }

        void _accelerometer_CurrentValueChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e)
        {
            Vector3 v = e.SensorReading.Acceleration;

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                _browser.InvokeScript("wp7ExtensionsaccelerometerChanged",
                (v.X * 9.81).ToString(System.Globalization.CultureInfo.InvariantCulture),
                (v.Y * 9.81).ToString(System.Globalization.CultureInfo.InvariantCulture),
                (v.Z * 9.81).ToString(System.Globalization.CultureInfo.InvariantCulture),
                _accelerometer.TimeBetweenUpdates.Milliseconds.ToString(System.Globalization.CultureInfo.InvariantCulture)
                );
            });
        }


        void browser_ScriptNotify(object sender, NotifyEventArgs e)
        {
            MessageBox.Show(e.Value);
        }

        public void Dispose()
        {
            if (_accelerometer != null)
            {
                _accelerometer.Stop();
                _accelerometer.Dispose();
            }
            if (_browser != null)
                _browser.ScriptNotify -= browser_ScriptNotify;
        }
    }
}
